package com.integrate.mybatis.config.druid;

import com.alibaba.druid.pool.DruidDataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * @author 刘志强
 * @date 2020/11/27 14:02
 * com.integrate.multiple.sources.mapper.consumer 生效范围
 */
@Component
@Slf4j
public class DataSourceConfiguration implements CommandLineRunner {

    @Autowired
    private Environment env;

    @Autowired
    private DataSource dataSource;


    @Override
    public void run(String... args) throws Exception {
        // 配置链接池信息
        log.info("数据源连接池配置");
        String prefixPool = "spring.datasource.";
        Properties prop = new Properties();
        prop.put("druid.initialSize", env.getProperty(prefixPool + "initialSize", String.class));
        prop.put("druid.maxActive", env.getProperty(prefixPool + "maxActive", String.class));
        prop.put("druid.minIdle", env.getProperty(prefixPool + "minIdle", String.class));
        prop.put("druid.maxWait", env.getProperty(prefixPool + "maxWait", String.class));
        prop.put("druid.poolPreparedStatements", env.getProperty(prefixPool + "poolPreparedStatements", String.class));
        prop.put("druid.maxPoolPreparedStatementPerConnectionSize", env.getProperty(prefixPool + "maxPoolPreparedStatementPerConnectionSize", String.class));
        prop.put("druid.validationQuery", env.getProperty(prefixPool + "validationQuery", String.class));
        prop.put("druid.validationQueryTimeout", env.getProperty(prefixPool + "validationQueryTimeout", String.class));
        prop.put("druid.testOnBorrow", env.getProperty(prefixPool + "testOnBorrow", String.class));
        prop.put("druid.testOnReturn", env.getProperty(prefixPool + "testOnReturn", String.class));
        prop.put("druid.testWhileIdle", env.getProperty(prefixPool + "testWhileIdle", String.class));
        prop.put("druid.timeBetweenEvictionRunsMillis", env.getProperty(prefixPool + "timeBetweenEvictionRunsMillis", String.class));
        prop.put("druid.minEvictableIdleTimeMillis", env.getProperty(prefixPool + "minEvictableIdleTimeMillis", String.class));
        prop.put("druid.filters", env.getProperty(prefixPool + "filters", String.class));

        DruidDataSource druidDataSource = (DruidDataSource) dataSource;
        druidDataSource.configFromPropety(prop);
        // 数据库初始化
        druidDataSource.init();
        log.info("数据源初始化结束");
    }
}
